<template>
  <div
    :class="[
      'elan-person-selector',
      { 'is-dialog': component === 'el-dialog' },
    ]"
  >
    <component
      :is="component"
      v-bind="$attrs"
      v-on="$listeners"
      :title="title"
      :visible="visible"
      :direction="direction"
      :append-to-body="appendToBody"
      :class="[
        { 'elan-person-selector': appendToBody === true },
        { 'is-dialog': component === 'el-dialog' },
      ]"
      :wrapper-closable="false"
      @close="handleCancel"
    >
      <el-row class="my-person-row">
        <el-col :span="6" class="my-col my-col1 dept">
          <el-tree
            v-if="visible"
            :data="data"
            ref="tree"
            node-key="dept_id"
            :props="defaultProps"
            @node-click="handleNodeClick"
            :default-expanded-keys="defaultExpandedKeys"
          ></el-tree>
        </el-col>
        <el-col :span="5" class="my-col my-col1" style="overflow-y: hidden">
          <div class="top-sum">
            <span class="select-title"
              >已选：<span class="my-blue">{{ sArr.length }}</span
              >人</span
            >
            <span class="clear" @click="handleClear">
              清空
              <i class="el-icon-delete delete"></i>
            </span>
          </div>
          <div style="height: calc(100% - 30px); overflow-y: auto">
            <p v-for="(item, index) in sArr" :key="item.id" class="select-item">
              <el-tag
                size="small"
                closable
                style="max-width: 120px"
                @close="handleDeleteTag(item, index)"
                >{{ item.name }}</el-tag
              >
            </p>
          </div>
        </el-col>
        <el-col :span="13" class="my-col my-col2" style="padding: 16px 12px">
          <div class="search-wrapper" style="margin-bottom: 12px">
            <el-input
              size="mini"
              placeholder="输入用户姓名/拼音"
              prefix-icon="el-icon-search"
              v-model="searchVal"
            ></el-input>
          </div>
          <el-table
            :data="tData"
            header-cell-class-name="my-header"
            height="calc(100% - 40px)"
            style="width: 100%"
            aria-setsize="mini"
            @select="handleRowSelect"
            @select-all="handleAllSelect"
            ref="table"
            stripe
            v-loading="loading"
          >
            <el-table-column type="selection" width="70"></el-table-column>
            <el-table-column
              label="姓名"
              prop="name"
              width="85"
            ></el-table-column>
            <el-table-column
              label="部门"
              prop="dept"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column label="状态" min-width="60">
              <template v-slot="scope">
                <span v-html="scope.row.state"></span>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <div class="footer">
        <!-- <el-button @click="handleMultiple" type="ghost">批量导入</el-button> -->
        <el-button @click="handleCancel" style="margin-left: auto"
          >取 消</el-button
        >
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </component>

    <el-dialog
      title="批量导入用户"
      :visible="multipleVisible"
      :before-close="handleMultipleClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :append-to-body="true"
      width="500px"
    >
      <el-input
        v-model="multipleName"
        type="textarea"
        :rows="6"
        placeholder="可输入多个用户姓名，用空格/英文逗号/中文逗号/顿号分隔"
      ></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleMultipleClose">关 闭</el-button>
        <el-button
          type="primary"
          @click="handleMultipleConfirm"
          :loading="multipleLoading"
        >
          {{ multipleLoading ? "匹配中..." : "保 存" }}
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getOrgPerson, getOrgTreeOld, getUserList } from "@/api";

const delay = (function() {
  let timer = 0;
  return function(callback, ms) {
    clearTimeout(timer);
    timer = setTimeout(callback, ms);
  };
})();
export default {
  props: {
    title: {
      type: String,
      default: "选择用户",
    },
    direction: {
      type: String,
      default: "rtl",
    },
    component: {
      type: String,
      default: "el-dialog",
    },
    visible: {
      type: Boolean,
      default: false,
    },
    selectedArr: {
      type: Array,
      default: () => {
        return [];
      },
    },
    appendToBody: {
      type: Boolean,
      default: true,
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    canZero: {
      // 是否可以选择0个用户点击保存
      type: Boolean,
      default: false,
    },
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    visible: {
      handler(newVal) {
        if (newVal) {
          if (process.env.NODE_ENV == "development") {
            this.userId = "7153";
          } else {
            this.userId = JSON.parse(
              sessionStorage.getItem("userInfo")
            ).user_id;
          }
          if (this.data.length === 0) {
            // this.getDeptEmpList()
            this.getOrgTreeData();
          }
          this.sArr = JSON.parse(JSON.stringify(this.selectedArr));
          // 获取表格数据
          this.getTableData("", "");
        }
      },
      immediate: true,
    },
    sArr: {
      handler(val) {
        if (!this.multiple && val.length > 1) {
          // this.$alert("最多只可选择一人");
          const row = val.shift();
          this.$refs.table.toggleRowSelection(row, false);
        }
      },
      immediate: true,
    },
    searchVal() {
      delay(() => {
        this.handleSearch();
      }, 500);
    },
  },
  data() {
    return {
      data: [],
      defaultProps: {
        children: "gpc_second_class",
        label: "dept",
      },
      defaultExpandedKeys: [],
      searchVal: "",
      sArr: [],
      tData: [],
      loading: false,
      deptNameOptions: [],
      selectPerson: [], //选中的人
      userId: "",
      multipleVisible: false,
      multipleLoading: false,
      multipleName: "",
    };
  },
  methods: {
    handleNodeClick(node) {
      console.log(node);
      // if(!node.gpc_second_class || (node.gpc_second_class && node.gpc_second_class.length === 0)) {
      // 点击的是叶子节点，调接口获取部门下的人
      this.getTableData(node.dept_id, "");
      // }
    },
    handleSearch() {
      this.getTableData("", this.searchVal);
    },
    handleRowSelect(selection, row) {
      const t = this.sArr.map((item) => parseInt(item.id));

      if (t.includes(parseInt(row.id))) {
        // 已存在于已选列表
        const index = this.sArr.findIndex((item) => item.id == row.id);
        this.sArr.splice(index, 1);
      } else {
        this.sArr.push(row);
      }
    },
    handleAllSelect(selection) {
      const t = this.sArr.map((item) => parseInt(item.id));
      if (selection.length > 0) {
        // 全选   // 此处的selection就相当于是tData
        // 已经存在于sArr中的不要重复push
        selection.forEach((item) => {
          if (!t.includes(parseInt(item.id))) {
            this.sArr.push(item);
          }
        });
      } else {
        // 取消全选
        this.tData.forEach((item) => {
          if (t.includes(parseInt(item.id))) {
            const index = this.sArr.findIndex((i) => i.id == item.id);
            this.sArr.splice(index, 1);
          }
        });
      }
    },
    getOrgTreeData() {
      getOrgTreeOld().then((res) => {
        this.data = res.data;
      });
    },
    getTableData(dept_id, search_kw) {
      this.tData = [];
      this.loading = true;
      getOrgPerson({
        deptId: dept_id,
        searchKey: search_kw,
        userId: this.userId,
      }).then((res) => {
        this.loading = false;
        this.tData = res.data || [];
        this.handleCheckSelected();
      });
    },
    // 检查当前表格数据是否有存在于已选列表中的，需要手动切换为已选状态
    handleCheckSelected() {
      const t = this.sArr.map((item) => parseInt(item.id));

      // 遍历当前的表格数据
      this.$nextTick(() => {
        this.tData.forEach((item) => {
          if (t.includes(parseInt(item.id))) {
            this.$refs.table.toggleRowSelection(item, true);
          } else {
            this.$refs.table.toggleRowSelection(item, false);
          }
        });
      });
    },
    handleDeleteTag(item, index) {
      // 从tData中取消选中item对应的row（如果item在tData中的话）
      const row = this.tData.find((row) => item.id == row.id);
      this.$refs.table.toggleRowSelection(row, false);
      this.sArr.splice(index, 1);
    },
    handleCancel() {
      this.sArr = [];
      this.tData = [];
      this.searchVal = "";
      this.$emit("update:visible", false);
      this.$emit("cancel");
    },
    handleSubmit() {
      if (!this.multiple && this.sArr.length > 1) {
        this.$alert("最多只可选择一人");
        return false;
      }

      if (this.sArr.length === 0 && !this.canZero) {
        this.$message.warning("请选择用户");
        return false;
      }
      this.$emit("update:visible", false);
      this.$emit("confirm", this.sArr);
      this.handleCancel();
    },
    handleClear() {
      this.sArr = [];
      this.handleCheckSelected();
    },
    handleMultiple() {
      this.multipleVisible = true;
    },
    handleMultipleClose() {
      this.multipleVisible = false;
      this.multipleName = "";
    },
    handleMultipleConfirm() {
      if (!this.multipleName) return;
      // 换行符替换为英文逗号
      let nameAll = this.multipleName.replace(/\n/g, ",");
      this.multipleLoading = true;
      console.log(nameAll, "0000");
      getUserList({
        nameAll,
      })
        .then((res) => {
          let data = [];
          (res.data || []).forEach((i) => {
            data.push({
              id: i.userId,
              name: i.userEmpName,
            });
          });
          this.sArr = [...this.sArr, ...data].filter((item, index, self) => {
            return self.findIndex((el) => el.id === item.id) === index;
          });
          this.handleMultipleClose();
          this.handleCheckSelected();
        })
        .finally((_) => {
          this.multipleLoading = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.top-sum {
  display: flex;
  justify-content: space-between;
  margin: 0 20px 14px 20px;
}
.elan-person-selector .clear {
  cursor: pointer;
}
.elan-person-selector .clear:hover,
.my-blue {
  color: rgba(28, 91, 226, 0.6);
}
.elan-search {
  margin-bottom: 12px;
}
.select-item {
  margin: 6px 20px 0 20px;
  display: flex;
}
::v-deep .el-dialog__header {
  border-bottom: 1px solid $grey-2;
}
</style>

<style scoped>
.my-dialog1 >>> .el-dialog__body {
  padding: 0 20px !important;
}
.my-col {
  height: 100%;
  overflow-y: auto;
}
.my-col1 {
  border-right: 1px solid #ededed;
  padding: 20px 0;
  box-sizing: border-box;
}
.my-col1.dept {
  padding: 14px 20px;
}
.my-col2 {
  padding-top: 20px;
  box-sizing: border-box;
}
.elan-person-selector.is-dialog ::v-deep .el-dialog__header {
  padding: 16px 20px;
  text-align: left;
}
.elan-person-selector.is-dialog ::v-deep .el-dialog__body {
  padding: 0;
}
.elan-person-selector ::v-deep .el-drawer__header {
  font-size: 16px;
  color: #333;
}
.elan-person-selector.is-dialog ::v-deep .my-person-row {
  height: 440px;
}
.elan-person-selector {
  font-size: 14px;
}
.elan-person-selector ::v-deep .el-drawer__header {
  text-align: left;
}
.elan-person-selector ::v-deep .my-person-row {
  height: calc(100vh - 120px);
}
.elan-person-selector ::v-deep .el-col {
  height: 100%;
}
.elan-person-selector .footer {
  display: flex;
  justify-content: flex-end;
  padding: 14px 24px;
  border-top: 1px solid #e8e8e8;
}
.elan-person-selector ::-webkit-scrollbar {
  width: 6px;
  height: 8px;
}
.elan-person-selector ::-webkit-scrollbar-track-piece {
  background-color: transparent;
  -webkit-border-radius: 6px;
}
.elan-person-selector ::-webkit-scrollbar-thumb:vertical {
  height: 5px;
  background-color: rgba(144, 147, 153, 0.3);
  -webkit-border-radius: 6px;
}
.elan-person-selector ::-webkit-scrollbar-thumb:horizontal {
  width: 6px;
  background-color: rgba(144, 147, 153, 0.3);
  -webkit-border-radius: 4px;
}
@media screen and (max-width: 1360px) {
  .elan-person-selector ::v-deep .el-drawer,
  .elan-person-selector ::v-deep .el-dialog {
    width: 60% !important;
  }
}
@media screen and (min-width: 1360px) and (max-width: 1560px) {
  .elan-person-selector::v-deep .el-drawer,
  .elan-person-selector ::v-deep .el-dialog {
    width: 50% !important;
  }
}
@media screen and (min-width: 1560px) {
  .elan-person-selector ::v-deep .el-drawer,
  .elan-person-selector ::v-deep .el-dialog {
    width: 45% !important;
  }
}
.elan-person-selector .el-table--border::after,
.elan-person-selector .el-table--group::after,
.el-table::before {
  display: none;
}
.elan-person-selector .el-tree {
  display: inline-block !important;
  min-width: 100%;
}
</style>
